// src/hooks/useMediaPlayerStream.js
import {useRef, useState, useCallback} from 'react';

export default function useMediaPlayerStream() {
  const queueRef = useRef([]); // 播放队列
  const isPlayingRef = useRef(false);
  const [isPlaying, setIsPlaying] = useState(false);

  // 播放单个 chunk
  const playAudioChunk = useCallback(async (pcmBase64) => {
    const sampleRate = 24000;
    const numChannels = 1;
    const binary = atob(pcmBase64);
    const pcmData = new Uint8Array(binary.length);
    for (let i = 0; i < binary.length; i++) {
      pcmData[i] = binary.charCodeAt(i);
    }
    const pcm16 = new Int16Array(pcmData.buffer);
    const float32 = new Float32Array(pcm16.length);
    for (let i = 0; i < pcm16.length; i++) {
      float32[i] = pcm16[i] / 32768;
    }
    const audioCtx = new window.AudioContext();
    const audioBuffer = audioCtx.createBuffer(numChannels, float32.length, sampleRate);
    audioBuffer.getChannelData(0).set(float32);
    const source = audioCtx.createBufferSource();
    source.buffer = audioBuffer;
    source.connect(audioCtx.destination);
    source.start();
    return new Promise((resolve) => {
      source.onended = () => {
        audioCtx.close();
        resolve();
      };
    });
  }, []);

  // 播放队列
  const playNext = useCallback(async () => {
    if (queueRef.current.length === 0) {
      isPlayingRef.current = false;
      setIsPlaying(false);
      return;
    }
    isPlayingRef.current = true;
    setIsPlaying(true);
    const next = queueRef.current.shift();
    await playAudioChunk(next);
    await playNext();
  }, [playAudioChunk]);

  // 外部调用：每收到一个 chunk 就调用
  const pushChunk = useCallback((pcmBase64) => {
    queueRef.current.push(pcmBase64);
    if (!isPlayingRef.current) {
      playNext();
    }
  }, [playNext]);

  return {pushChunk, isPlaying};
}